* Clean and Combine Data Files

*AGGREGATE ENIA F3 DATA TO 3-DIGIT LEVEL
do f3_agg

*AGGREGATE CUSTOMS DATA TO 3-DIGIT LEVEL
do customs_agg

*MAIN ENIA DATA (F1)
use "ENIA_F1", clear
sort CIIU3_3D ID_F ID_P A�O
rename A�O year
*Aggregate to firm level
do f1_clean
sort ID_FIRMA year
save f1, replace

*ADDITIONAL ENIA DATA (F3)
use "ENIA_F3", clear
rename AÑO year 
rename CIIU3_3D_FIRMA CIIU3_3D
save f3_raw, replace
*Aggregate to firm level
do f3_clean
sort ID_FIRMA year
save f3, replace

*CUSTOMS DATA
use "Exports", clear
rename AÑO year
rename CIIU_Rev3_FIRMA ind_cust
label variable fob_x_ijtu "FOB (Thousands $) (Customs office)"
label variable q_fob_x_ijtu "Quantity (Customs office)"  
sort ID_FIRMA year N_ID_PRODUCTO ad_measu_unit_ijtu
save cust, replace

*DEFLATORS
use deflactores, clear
rename A�O year
sort year
save deflators, replace

*INTERMEDIATE INPUT USAGE AND DEFLATORS
use "ENIA_F4", clear
rename AÑO year
rename defl_inputs_branch_ciiu_v1 defl_inputs
rename defl_inputs_branch_ciiu_v2 defl_inputs_2
rename defl_inputs_branch_ciiu_v3 defl_inputs_3
rename defl_inputs_branch_ciiu_v4 defl_inputs_4
drop CIIU*
save f4_input_raw, replace
do f4_clean 
sort ID_FIRMA year
save f4_input, replace

*MERGE CLEANED RAW DATA FILES
use f3
merge ID_FIRMA year using f4_input
drop _m

sort ID_FIRMA year
merge ID_FIRMA year using f1
drop _m
sort ID_FIRMA year N_ID_PRODUCTO 
merge ID_FIRM year N_ID_PRODUCTO using cust
drop _m

rename ID_FIRMA firm_id
rename N_ID_PRODUCTO cpc3


*SAVE MERGED DATASET
save merged, replace



